package com.xuecheng.mybatis.config;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.xuecheng.commons.utils.AuthInfoHolder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyBatisPlusConfig {

   //不需要多租户的表
   private static String[] tables=new String[]{"tb_dictionary","tb_category","undo_log",
   "tb_application","tb_company","tb_resource","tb_role_resource","tb_user_role"};

   //注册mybatis的插件
   @Bean
   public MybatisPlusInterceptor mybatisPlusInterceptor() {
      MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
      interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
         //获取租户id
         @Override
         public Expression getTenantId() {
            //通过TL获取登陆人企业id
            Long companyId = AuthInfoHolder.getCompanyId();
            if(companyId==null){
               return null;
            }
            return new LongValue(companyId);
         }

         //表中租户字段

         @Override
         public String getTenantIdColumn() {
            return "company_id";
         }

         /*
         * 判断表是否添加多租户查询
         * false：添加
         * true:忽略(不添加)
         * */

         @Override
         public boolean ignoreTable(String tableName) {
            //1.登陆人没有企业id,忽略
            if(getTenantId()==null){
               return true;
            }
            //2.以下表忽略
            if(ArrayUtil.containsIgnoreCase(tables,tableName)){
               return true;
            }
            //其余都添加多租户id
            return false;
         }
      }));
      interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
      return interceptor;
   }
}